#encoding:utf-8
'''
FileName:channel.py
Creator:王烨
Date:2010.5.23
'''
import uuid
from google.protobuf.service import RpcChannel
from google.protobuf.message import DecodeError
from rpc_pb2 import *
from error import *

class Channel(RpcChannel):
    '''RPC调用信道的实现'''
    def __init__(self):
        RpcChannel.__init__(self)
        
    def SerializeParameters(self, methodDescriptor, parameters):
        uuidMethod = uuid.uuid4().hex
        request = Request()
        request.uuid = uuidMethod
        request.serviceName = methodDescriptor.containing_service.name
        request.methodName = methodDescriptor.name
        request.parameters = parameters.SerializeToString()
        return (uuidMethod, request.SerializeToString())
    
    def DeserializeResponse(self, data):
        response = Response()
        try:
            response.ParseFromString(data)
        except DecodeError:
            raise ProtobufError(BAD_RESPONSE_DATA, 'Fail to deserialize RPC response')
        if not response.IsInitialized():
            raise ProtobufError(BAD_RESPONSE_PROTOCOL, 'Bad RPC response')
        print '反序列化响应完成'
        return response
            
    def DeserializeResult(self, response, resultClass, controller):
        '''接收到RPC调用回复后，反序列化RPC响应'''
        if response.error:
            err = response.error[0]
            print '开始处理错误响应'
            if err.type == RPC_FAIL:
                controller.SetFailed(err.type, err.text)
                return
            else:
                raise ProtobufError(err.type, err.text)
            
        print '开始反序列化返回值'
        result = resultClass()
        try:
            result.ParseFromString(response.result)
        except DecodeError:
            raise ProtobufError(BAD_RESPONSE_DATA, 'Fail to deserialize RPC response')
        if not response.IsInitialized():
            raise ProtobufError(BAD_RESPONSE_PROTOCOL, 'Bad RPC response')
            
        print '返回值反序列化完成'
        return result
    
   